using System.Linq;
using Shop.Backend.Api.Entity;
using Shop.Backend.Api.Params;
using Shop.Backend.Api.Repository;
using Shop.Backend.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System;

namespace Shop.Backend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class GoodsController : ControllerBase
    {
        private IConfiguration _configuration;
        private IRepository<Users> _usersRepository;
        private IRepository<Goods> _goodsRepository;
        private IRepository<Shops> _shopsRepository;
        private IRepository<GoodsBrands> _goodsBrandsRepository;
        private IRepository<Suppliers> _suppliersRepository;
        private IRepository<GoodsCategory1> _goodsCategory1Repository;
        private IRepository<GoodsCategory2> _goodsCategory2Repository;
        private IRepository<GoodsCategory3> _goodsCategory3Repository;
        private IRepository<GoodsSKU> _goodsSKURepository;
        private IRepository<GoodsImages> _goodsImageRepository;


        private TokenParameter _tokenParameter;


        public GoodsController(IConfiguration configuration
        , IRepository<Users> usersRepository
        , IRepository<Goods> goodsRepository
        , IRepository<Shops> shopsRepository
        , IRepository<GoodsBrands> goodsBrandsRepository
        , IRepository<Suppliers> suppliersRepository
        , IRepository<GoodsCategory1> goodsCategory1Repository
        , IRepository<GoodsCategory2> goodsCategory2Repository
        , IRepository<GoodsCategory3> goodsCategory3Repository
        , IRepository<GoodsImages> goodsImageRepository
        , IRepository<GoodsSKU> goodsSKURepository)

        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _goodsRepository = goodsRepository;
            _shopsRepository = shopsRepository;
            _goodsBrandsRepository = goodsBrandsRepository;
            _suppliersRepository = suppliersRepository;
            _goodsCategory1Repository = goodsCategory1Repository;
            _goodsCategory2Repository = goodsCategory2Repository;
            _goodsCategory3Repository = goodsCategory3Repository;
            _goodsSKURepository = goodsSKURepository;
            _goodsImageRepository = goodsImageRepository;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        [HttpGet]
        public dynamic Get([FromQuery] QueryWithPager query)
        {
            // get请求默认从url中获取参数，如果需要使用实体接收参数，需要FromQuery特性
            var pageIndex = query.Pager.PageIndex;
            var pageSize = query.Pager.PageSize;

            var keyword = string.IsNullOrEmpty(query.Keyword) ? "" : query.Keyword.Trim();

            var goods = _goodsRepository.Table.ToList()
            .Where(x => x.IsDeleted == false)
            .Select(a =>
            {
                var shop = _shopsRepository.Table.ToList().Where(x => x.Id == a.FromShopsId).FirstOrDefault();//拿到商店名字
                var supplier = _suppliersRepository.Table.ToList().Where(x => x.Id == a.FromSupplierId).FirstOrDefault();
                var brand = _goodsBrandsRepository.Table.ToList().Where(x => x.Id == a.FromGoodsBrandsId).FirstOrDefault();
                var category1 = _goodsCategory1Repository.Table.ToList().Where(x => x.Id == a.FromGoodsCategory1Id).FirstOrDefault();
                var category2 = _goodsCategory2Repository.Table.ToList().Where(x => x.Id == a.FromGoodsCategory2Id).FirstOrDefault();
                var category3 = _goodsCategory3Repository.Table.ToList().Where(x => x.Id == a.FromGoodsCategory3Id).FirstOrDefault();

                return new
                {
                    Id = a.Id,
                    GoodsName = a.GoodsName,
                    ShopName = shop.ShopName,
                    SupplierName = supplier.SuppliersName,
                    BrandName = brand.BrandsName,
                    category1Name = category1.CategoryName,
                    category2Name = category2.CategoryName,
                    category3Name = category3.CategoryName,
                    OldPrice = a.Price,
                    NewPrice = a.NowPrice,
                    GoodsNumber = a.GoodsNumber,
                    GoodsStock = a.GoodsStock,
                    GoodsDesc = a.GoodsDesc,
                    GoodsState = a.GoodsState,
                    CreatedTime = a.CreatedTime,
                    IsActived = a.IsActived,
                    GoodsImage = a.GoodsImage
                };
            });


            // 如果keyword不为空，则再去查询商品
            if (!string.IsNullOrEmpty(keyword))
            {
                goods = goods.Where(x => x.Id.ToString() == keyword
                || x.GoodsName.Contains(keyword)
                || x.ShopName.Contains(keyword)
                || x.SupplierName.Contains(keyword)
                || x.category1Name.Contains(keyword)
                || x.category2Name.Contains(keyword)
                || x.category3Name.Contains(keyword)
                || x.GoodsStock.ToString() == (keyword)
                || x.GoodsNumber.ToString() == (keyword)
                || x.GoodsDesc.Contains(keyword));
            }
            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = new
                {
                    Data = goods,
                    Pager = new
                    {
                        pageIndex,
                        pageSize,
                        rowsTotal = goods.Count()
                    }
                },
                Msg = "获取商品列表成功^_^"
            });
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var goods = _goodsRepository.Table.ToList().Where(x => x.Id == id).Select(a =>
                {
                    var shop = _shopsRepository.Table.ToList().Where(x => x.Id == a.FromShopsId).FirstOrDefault();//拿到商店名字
                    var supplier = _suppliersRepository.Table.ToList().Where(x => x.Id == a.FromSupplierId).FirstOrDefault();
                    var brand = _goodsBrandsRepository.Table.ToList().Where(x => x.Id == a.FromGoodsBrandsId).FirstOrDefault();
                    var category1 = _goodsCategory1Repository.Table.ToList().Where(x => x.Id == a.FromGoodsCategory1Id).FirstOrDefault();
                    var category2 = _goodsCategory2Repository.Table.ToList().Where(x => x.Id == a.FromGoodsCategory2Id).FirstOrDefault();
                    var category3 = _goodsCategory3Repository.Table.ToList().Where(x => x.Id == a.FromGoodsCategory3Id).FirstOrDefault();
                    var images = _goodsImageRepository.Table.ToList().Where(x => x.FromGoodsId == a.Id);


                    return new
                    {
                        Id = a.Id,
                        GoodsName = a.GoodsName,
                        ShopName = shop.ShopName,
                        SupplierName = supplier.SuppliersName,
                        BrandName = brand.BrandsName,
                        category1Name = category1.CategoryName,
                        category2Name = category2.CategoryName,
                        category3Name = category3.CategoryName,
                        OldPrice = a.Price,
                        NewPrice = a.NowPrice,
                        GoodsStock = a.GoodsStock,
                        GoodsDesc = a.GoodsDesc,
                        GoodsState = a.GoodsState,
                        CreatedTime = a.CreatedTime,
                        IsActived = a.IsActived,
                        images = images,
                        GoodsImages = a.GoodsImage,
                        GoodsNumber = a.GoodsNumber,

                    };
                });

            return new
            {
                Code = 1000,
                Data = goods,
                Msg = "获取指定商品成功^_^"
            };
        }

        [HttpPost]
        public dynamic Post(CreateGoods createGoods)
        {
            var goodsName = createGoods.GoodsName.Trim();

            if (string.IsNullOrEmpty(goodsName))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "商品名不能为空"
                };
            }

            var goodsNumber = DateTime.Now.Year.ToString().Substring(2, 2) + DateTime.Now.Month.ToString().PadLeft(2, '0')
                        + DateTime.Now.Day.ToString().PadLeft(2, '0') + DateTime.Now.Hour.ToString().PadLeft(2, '0')
                        + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                        + DateTime.Now.ToString("fff");

            var goods = new Goods
            {
                GoodsName = createGoods.GoodsName,
                FromShopsId = 0,
                FromSupplierId = 0,
                FromGoodsBrandsId = 0,
                FromGoodsCategory1Id = 0,
                FromGoodsCategory2Id = 0,
                FromGoodsCategory3Id = 0,
                GoodsNumber = goodsNumber,//商品编号
                GoodsImage = createGoods.GoodsImage,//商品图片
                Price = createGoods.Price,
                NowPrice = createGoods.Price,
                GoodsStock = createGoods.GoodsStock,//库存
                GoodsDesc = createGoods.GoodsDesc,//简介
                GoodsState = createGoods.GoodsState,//是否上架
            };




            //查一查  如果存在就判断 如果是的话 就赋值  不是的话就返回报错信息

            //通过前端传来的商铺名称查找相对应的店铺Id

            var shop = _shopsRepository.Table.ToList().Where(x => x.ShopName == createGoods.FromShopsName && x.IsDeleted == false);

            if (shop.Count() > 0)
            {
                //如果存在的话 就赋值咯
                goods.FromShopsId = shop.FirstOrDefault().Id;
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该 商铺 不存在，请检查后重试‘.’"
                };
            }

            //通过前端传来的供应商名称 查找对应的供应商id
            var supplier = _suppliersRepository.Table.ToList().Where(x => x.SuppliersName == createGoods.FromSupplierName && x.IsDeleted == false);
            if (supplier.Count() > 0)
            {
                //存在
                goods.FromSupplierId = supplier.FirstOrDefault().Id;
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该 供应商 不存在，请检查后重试‘.’"
                };
            }

            //通过传来的品牌名称 查找对应的品牌
            var brand = _goodsBrandsRepository.Table.ToList().Where(x => x.BrandsName == createGoods.FromGoodsBrandsName && x.IsDeleted == false);
            if (brand.Count() > 0)
            {
                //存在
                goods.FromGoodsBrandsId = brand.FirstOrDefault().Id;
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该 品牌 不存在，请检查后重试‘.’"
                };
            }

            //通过 前端传来的分类 查找对应是否存在 
            var category1 = _goodsCategory1Repository.Table.ToList().Where(x => x.CategoryName == createGoods.FromGoodsCategory1Name);
            var category2 = _goodsCategory2Repository.Table.ToList().Where(x => x.CategoryName == createGoods.FromGoodsCategory2Name);
            var category3 = _goodsCategory3Repository.Table.ToList().Where(x => x.CategoryName == createGoods.FromGoodsCategory3Name);
            if (category1.Count() * category2.Count() * category3.Count() > 0)
            {
                goods.FromGoodsCategory1Id = category1.FirstOrDefault().Id;
                goods.FromGoodsCategory2Id = category2.FirstOrDefault().Id;
                goods.FromGoodsCategory3Id = category3.FirstOrDefault().Id;
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该商品的 分类 不存在，请检查后重试‘.’"
                };
            }
            //同时我也要添加商品的sku （规格)


            //规格名称  规格  例如 颜色 :红色  

            //{prop1 :["红色"，"白色","绿色"]，prop2 :["128G"，"64G","256G"]}

            var test = new
            {
                Color = new
                {
                    Color1 = "红色",
                    Color2 = "白色",
                    Color3 = "绿色"
                },
                Fontsize = new
                {
                    Fontsize1 = "64G",
                    Fontsize2 = "128G",
                    Fontsize3 = "256G"
                }

            };
            // var red = test.Color.Color1;
            // var white = test.Color.Color2;
            // JsonHelper.Serialize(test);

            // //序列化
            // var cat1 = new GoodsSKU { SKUName = JsonHelper.Serialize(test), FromGoodsId = 1 };//前端传来的json对象//new GoodsSKU { Color = "Write", Speed = 50, Name = "MiMi" };
            // XmlSerializer ser = new XmlSerializer(typeof(GoodsSKU));
            // MemoryStream ms = new MemoryStream();
            // ser.Serialize(ms, cat1);
            // string xmlString = Encoding.UTF8.GetString(ms.ToArray());
            // //xmlString就是你要保存到数据库的字符串

            var SKU = new GoodsSKU
            {
                FromGoodsId = createGoods.Id,
                SKUName = JsonHelper.Serialize(test)//xmlString
            };
            _goodsSKURepository.Insert(SKU);

            //     //反序列化
            //     XmlSerializer dser = new XmlSerializer(typeof(GoodsSKU));
            // //xmlString是你从数据库获取的字符串
            // Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
            // GoodsSKU cat2 = dser.Deserialize(xmlStream) as GoodsSKU;//cat2 就是你要得到的class对象



            //--------------------------------------------//

            // if (string.IsNullOrEmpty(skuName))
            // {
            //     return new
            //     {
            //         Code = 104,
            //         Data = "",
            //         Msg = "请添加商品的规格"
            //     };
            // }



            // //反序列化
            // XmlSerializer dser = new XmlSerializer(typeof(GoodsSKU));
            // //xmlString是你从数据库获取的字符串
            // Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
            // GoodsSKU cat2 = dser.Deserialize(xmlStream) as GoodsSKU;//cat2 就是你要得到的class对象

            if (goods.FromShopsId
            * goods.FromSupplierId
            * goods.FromGoodsBrandsId
            * goods.FromGoodsCategory1Id
            * goods.FromGoodsCategory2Id
            * goods.FromGoodsCategory3Id > 0)
            {
                _goodsRepository.Insert(goods);


            }

            foreach (var item in createGoods.Image)
            {
                var goodsImages = new GoodsImages
                {
                    FromGoodsId = goods.Id,
                    GoodsImagesPath = item
                };
                _goodsImageRepository.Insert(goodsImages);
            }



            return new
            {
                Code = 1000,
                Data = goods,
                SKU = SKU,
                // Cat2 = cat2,
                // Test = test,
                // Red = red,
                // White = white,
                Msg = "添加商品成功^_^"
            };

        }
        //伪删除商品
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {

            var goods = _goodsRepository.GetById(id);

            if (goods == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "删除品牌不存在O.O"
                };

            }

            goods.IsActived = false;
            goods.IsDeleted = true;
            _goodsRepository.Update(goods);

            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除品牌成功^_^"

            };
        }
        [HttpPut, Route("status")]
        public dynamic PutStatus(CreateGoods updateGoods)
        {
            var Id = updateGoods.Id;
            var user = _goodsRepository.GetById(Id);


            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的商品不存在，请确认后重试=_="
                };
            }

            user.IsActived = updateGoods.IsActived;
            _goodsRepository.Update(user);

            return new
            {
                Code = 1000,
                Data = user,
                Msg = "更新成功"
            };
        }

        //编辑指定商品
        [HttpPut("{id}")]
        public dynamic Put(int id, CreateGoods updateGoods)
        {
            var goodsName = updateGoods.GoodsName.Trim();

            //这里涉及到 多个表一起的修改 而且要符合表里的内容
            var goods = _goodsRepository.GetById(id);

            //例如
            //修改商品名称 可随意修改 但不能为空
            if (string.IsNullOrEmpty(goodsName))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "商品名称不能为空，修改商品名称失败O.O"
                };
            }
            else
            {
                goods.GoodsName = updateGoods.GoodsName;
            }

            //修改店铺的时候我需要去查找这家店铺是否存在 若存在继续向下若不存在 返回错误信息
            //此时我要有店铺了才能改 素所以要查有没有这个店
            var shop = _shopsRepository.Table.ToList().Where(x => x.ShopName == updateGoods.FromShopsName && x.IsDeleted == false).FirstOrDefault();
            if (shop == null)
            {
                //不存在
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该 店铺 不存在请核查后重试 O.O"
                };
            }
            else
            {
                goods.FromShopsId = shop.Id;
            }

            //修改供应商的时候也是需要去供应商表中查询是否有该供应商 若有 修改 若无 返回错误信息

            var supplier = _suppliersRepository.Table.ToList().Where(x => x.SuppliersName == updateGoods.FromSupplierName && x.IsDeleted == false).FirstOrDefault();
            if (supplier == null)
            {
                //不存在
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该 供应商 不存在请核查后重试 O.O"
                };
            }
            else
            {
                goods.FromSupplierId = supplier.Id;
            }

            //修改品牌时 也一样 需要去查询品牌表  有继续 无 报错
            var brand = _goodsBrandsRepository.Table.ToList().Where(x => x.BrandsName == updateGoods.FromGoodsBrandsName && x.IsDeleted == false).FirstOrDefault();
            if (brand == null)
            {
                //不存在
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该 品牌 不存在请核查后重试 O.O"
                };
            }
            else
            {
                goods.FromGoodsBrandsId = brand.Id;
            }

            /////修改分类 不实现  不让商家修改商品分类

            ////修改价钱
            /// 做判断 现价不能大于原价

            if (updateGoods.Price < updateGoods.NowPrice)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "一般来说商品 '原价' 不能低于商品 '现价' 请核对后修改O.O"
                };
            }
            else
            {
                //修改原价
                goods.Price = updateGoods.Price;

                //修改现价  
                goods.NowPrice = updateGoods.NowPrice;
            }

            //修改商品的库存  
            goods.GoodsStock = updateGoods.GoodsStock;


            if (shop != null && supplier != null && brand != null)
            {
                _goodsRepository.Update(goods);

                return new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "编辑商品成功^_^"
                };
            }

            return new
            {
                Code = 104,
                Data = "",
                Msg = "发生未知错误，编辑商品失败^_^"
            };
        }

    }
}